package com.ycj.entropy.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.ycj.entropy.R;
import com.ycj.entropy.data.DaoFactory;
import com.ycj.entropy.data.Study;
import com.ycj.entropy.data.StudyDao;
import com.ycj.entropy.util.StringUtil;

import java.util.List;
import java.util.Objects;

public class ListFragment extends Fragment {
    private StudyDao studyDao;
    private View root;
    private View btnQuery;
    private ClearEditText txtSearch;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        this.root = inflater.inflate(R.layout.fragment_list, container, false);
        init();
        refresh();
        return this.root;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refresh();
    }

    private void init() {
        DaoFactory.init(getActivity());
        this.studyDao = DaoFactory.studyDao();
        this.btnQuery = this.root.findViewById(R.id.list_btn_search);
        this.txtSearch = this.root.findViewById(R.id.list_txt_search);

        this.btnQuery.setOnClickListener(v -> {
            Editable txt = this.txtSearch.getText();
            if (txt != null) {
                this.refresh(this.studyDao.listByTitle(txt.toString()));
            }
        });

    }

    private void refresh() {
        List<Study> studies = this.studyDao.list();
        this.refresh(studies);
    }

    private void refresh(List<Study> studies) {
        FragmentActivity activity = getActivity();
        FragmentManager manager = Objects.requireNonNull(activity).getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        for (Fragment fragment : manager.getFragments()) {
            if (fragment instanceof ListItemFragment) {
                transaction.remove(fragment);
            }
        }

        for (Study study : studies) {
            ListItemFragment fragment = new ListItemFragment();
            fragment.setModel(study);
            transaction.add(R.id.list_study, fragment);
        }

        transaction.commit();
    }


}